<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 索赔结算单查询-编辑页面 -->
    <BreakSpace label="结算单汇总信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="padding-top: 3rem;"></div>
    <BreakSpace label="结算单列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="false"
      :isSelectColumn="false"
      :isPagination = false
      height="auto"
    >
<!--      <template slot="controls" slot-scope="props">-->
<!--        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="jiesuandanadd()">添加</multiuse-button>suopeidanadd-->
<!--      </template>-->
    </FilterTable>
<!--    <BaseDialog :visible.sync="jiesuandanFlag" :title="'结算单选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">-->
<!--      <SelectJieSuanDan @close="jiesuandanclose" @save="jiesuandansave"></SelectJieSuanDan>-->
<!--    </BaseDialog>-->
    <div style="padding-top: 3rem;"></div>
    <BreakSpace label="审核列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table1"
      :columns="columns1"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="false"
      :isSelectColumn="false"
      :isPagination = false
      height="auto"
    >
    </FilterTable>
    <div style="padding-top: 3rem;"></div>
    <!--审核说明-->
    <FormPanel ref="formPanel2" :list="formList2" :cols="4" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle2" />
    <div style="margin-bottom: 1rem;"></div>
    <div style="padding-top: 3rem;"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="tongguo.bind()">通 过</multiuse-button>
      <multiuse-button type="primary" :click="bohui.bind()">驳 回</multiuse-button>
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
    <Drawer :visible.sync="chakanFlag" :title="'结算单详情'" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <showDetail @close="chakanFlag=false" :rowData="rowDate"></showDetail>
    </Drawer>
  </div>
  </Spin>
</template>
<script>
  import {  getPartType,quyrPSettleSum,editSave } from '@/api/claim/factory/ClaimAccountSummaryCheck';
  import { isFormEmpty } from '@/utils/index';
  import { dictionary } from '@/utils/dictMixin';
  import showDetail from "../ClaimStatementQueryFactory/showDetail";
  export default {
    mixins: [dictionary],
    props: ['rowData'],
    components: {
      showDetail
    },
    data() {
      return {
        loading: false,
        dataList: [],
        editRow: {},
        yuanIds:'' ,
        visible: false,
        jiesuandanFlag: false,
        visibleDrawer: false,
        jiesuansum: 0,
        fapiaozhangshusum: 0,
        shenHeFlag: 0,
        collapse: false,
        infoId: null,
        flterValue: {}, //参数
        columns: this.creatHeader(),
        columns1: this.creatHeader1(),
        formList2: this.createFormList2(),
        fetchParams: {}, //ipa 接口
        selectedRows: [], //选中经销商
        formList: this.createFormList(),
        saveData: null,
        rowDate:null,
        chakanFlag:false
      };
    },
    async created() {
      this.loading = true;
      await this.chuqi();
      await this.chuqi2();
      await this.getDetailFun(this.rowData.sumId);
      this.loading = false;
    },
    methods: {
      //通过
      async tongguo() {
        this.shenHeFlag = 1;
        this.$refs.formPanel.SUBMIT_FORM();
        let arr = [];
        this.$refs.table.$refs.pageTable.list.map(x => {
          delete x.isDeleted;
          delete x.dtlId;
          arr.push(x);
        });
        console.log(666);
        console.log(this.$refs.table.$refs.pageTable.list);
        for (let a in this.editRow) {
          if (this.saveData[a]) {
            this.editRow[a] = this.saveData[a];
          }
        }
        //子表
        this.editRow.dtlList = arr;
        //审核记录不保存
        delete this.editRow.logList;
        delete this.editRow.batchList;
        this.editRow.delDtlIds = this.yuanIds;

        //通过1  驳回2
        if (this.shenHeFlag == 1) {
          this.editRow.sumStatus = 55471004;
        }
        if (this.shenHeFlag == 2) {
          this.editRow.sumStatus = 55471005;
        }

        this.$refs.formPanel2.SUBMIT_FORM();
        this.editRow = Object.assign(this.editRow, this.saveData2);

        if (this.editRow.dtlList.length !== 0 && this.saveData.sumType !== null) {
          this.loading = true;
          let res = await editSave(this.editRow);
          if (res.resultCode === 200) {
            this.$emit('save')
            return this.$notify.success({title: '提示信息', message: '保存成功'});
          } else {
            this.loading = false;
            this.$notify.error({title: '提示信息', message: res.errMsg || '保存失败!'});
            this.closeDialog();
          }
        } else {
          this.loading = false;
          return this.$notify.warning({title: '提示信息', message: '有未校验通过的信息'});
        }
      },

      //驳回
      async bohui() {
        this.formList2.find(x => x.fieldName === 'checkRemarks').rules = [{
          required: true,
          message: '请输入审核备注...',
          trigger: 'change'
        }];
        if (this.formList2.find(x => x.fieldName === 'checkRemarks').initialValue) {
          this.shenHeFlag = 2;
          this.$refs.formPanel.SUBMIT_FORM();
          let arr = [];
          this.$refs.table.$refs.pageTable.list.map(x => {
            delete x.isDeleted;
            delete x.dtlId;
            arr.push(x);
          });
          console.log(666);
          console.log(this.$refs.table.$refs.pageTable.list);
          for (let a in this.editRow) {
            if (this.saveData[a]) {
              this.editRow[a] = this.saveData[a];
            }
          }
          //子表
          this.editRow.dtlList = arr;
          //审核记录不保存
          delete this.editRow.logList;
          delete this.editRow.batchList;
          this.editRow.delDtlIds = this.yuanIds;

          //通过1  驳回2
          if (this.shenHeFlag == 1) {
            this.editRow.sumStatus = 55471004;
          }
          if (this.shenHeFlag == 2) {
            this.editRow.sumStatus = 55471005;
          }

          this.$refs.formPanel2.SUBMIT_FORM();
          this.editRow = Object.assign(this.editRow, this.saveData2);

          if (this.editRow.dtlList.length !== 0 && this.saveData.sumType !== null) {
            this.loading = true;
            let res = await editSave(this.editRow);
            if (res.resultCode === 200) {
              this.$emit('save');
              return this.$notify.success({title: '提示信息', message: '保存成功'});
            } else {
              this.loading = false;
              this.$notify.error({title: '提示信息', message: res.errMsg || '保存失败!'});
              this.closeDialog();
            }
          } else {
            this.loading = false;
            return this.$notify.warning({title: '提示信息', message: '有未校验通过的信息'});
          }
        } else {
          this.loading = false;
          return this.$notify.warning({title: '提示信息', message: '有未校验通过的信息'});
        }

      },
      formChangeHandle2(val) {
        this.saveData2 = val;
      },
      async getDetailFun(val) {
        let res= await quyrPSettleSum(val);
        this.editRow = res.data;

        this.jiesuansum=this.editRow.invoiceAmount;
        this.fapiaozhangshusum=this.editRow.invoiceSheets;
        //为form赋值
        for (let i in res.data) {
          this.formList.map(x => {
            if (x.fieldName == i) {
              x.initialValue = res.data[i];
            }
          });
        }
        //为table赋值
        if (200 == res.resultCode) {
          let data = res.data;
          if (isFormEmpty(data)) {
            data = {};
          }
          let records = data.batchList;
          if (isFormEmpty(records)) {
            records = [];
          }
          this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records);
          //取出ids
          let ids1 = [];
          this.$refs.table.$refs.pageTable.list.map(x => {
            ids1.push(x.dtlId);
          });
          let ids = '';
          ids1.map(x => {
            ids += x + ','
          });
          this.yuanIds = ids;
          console.log(this.yuanIds);
        }
        if (200 == res.resultCode) {
          let data = res.data;
          if (isFormEmpty(data)) {
            data = {};
          }
          let records1 = data.logList;
          if (isFormEmpty(records1)) {
            records1 = [];
          }
          this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(records1);
        }

      },
      //考核分类
      async chuqi2() {
        // const res = await getPartType({ type: 5543 });
        // if (res.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'sumType').initialValue = '';
        //   this.formList.find(x => x.fieldName == 'sumType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
      //结算单删除
      deleteFunjiesuan(costItem) {
        this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            this.$notify({
              title: '提示信息',
              message: '删除成功',
              type: 'success'
            });
            this.$refs.table.$refs.pageTable.EXECUTE_DELETE([costItem]);
            this.formList.map(x => {
              if ('invoiceAmount' == x.fieldName) {
                x.initialValue = this.jiesuansum - Number(costItem.settleSum);
                this.jiesuansum=this.jiesuansum - Number(costItem.settleSum);
              }
            });
            this.formList.map(x => {
              if ('invoiceSheets' == x.fieldName) {
                x.initialValue = this.fapiaozhangshusum - Number(costItem.invoiceSheets);
                this.fapiaozhangshusum=this.fapiaozhangshusum - Number(costItem.invoiceSheets);
              }
            });
          })
      },
      chakan(val) {
        this.rowDate = val;
        this.chakanFlag = true;
      },
      //结算单状态
      async chuqi() {
        // const res = await getPartType({ type: 5547 });
        // if (res.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'sumStatus').initialValue = '';
        //   this.formList.find(x => x.fieldName == 'sumStatus').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
      formChangeHandle(val) {
        console.log(val);
        this.saveData = val;
      },
      //搜索获取数据
      changeHandle(val) {
        this.fetchParams = val;
        console.log(val);
      },
      //结算单计算
      jiesuandansave(val) {
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(val);
        //总金额
        let jiesuanjine = 0;
        this.$refs.table.$refs.pageTable.list.map(x => {
          jiesuanjine += Number(x.settleSum);
        });
        this.formList.map(x => {
          if ('invoiceAmount' == x.fieldName) {
            x.initialValue = Number(jiesuanjine);
          }
        });
        this.jiesuansum=jiesuanjine;
        //发票张数
        let fapiaozhangshu = 0;
        this.$refs.table.$refs.pageTable.list.map(x => {
          fapiaozhangshu += Number(x.invoiceSheets);
        });
        this.formList.map(x => {
          if ('invoiceSheets' == x.fieldName) {
            x.initialValue = Number(fapiaozhangshu);
          }
        });
        this.fapiaozhangshusum=fapiaozhangshu;
        this.jiesuandanFlag = false;
      },
      suopeidanclose() {
        this.suopeidanFlag = false;
      },
      jiesuandanadd() {
        this.jiesuandanFlag = true;
      },
      jiesuandanclose() {
        this.jiesuandanFlag = false;
      },
      //选中
      selectChange(rows) {
        this.selectedRows = rows;
      },
      //保存
      async saveDialog() {
        this.$refs.formPanel.SUBMIT_FORM();
        let arr = [];
        this.$refs.table.$refs.pageTable.list.map(x => {
          delete x.isDeleted;
          delete x.dtlId;
          arr.push(x);
        });
        console.log(666);
        console.log(this.$refs.table.$refs.pageTable.list);
        for (let a in this.editRow) {
          if (this.saveData[a]) {
            this.editRow[a] = this.saveData[a];
          }
        }
        //子表
        this.editRow.dtlList = arr;
        //审核记录不保存
        delete this.editRow.logList;
        delete this.editRow.batchList;
        this.editRow.delDtlIds = this.yuanIds;

        //通过1  驳回2
        if(this.shenHeFlag==1){
          this.editRow.sumStatus=55471004;
        }
        if(this.shenHeFlag==2){
          this.editRow.sumStatus=55471005;
        }

        this.$refs.formPanel2.SUBMIT_FORM();
        this.editRow = Object.assign(this.editRow, this.saveData2);

        if (this.editRow.dtlList.length!==0&&this.saveData.sumType!==null) {
          let res = await editSave(this.editRow);
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
            this.$emit('save');
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }
        }else {
          return this.$notify.warning({ title: '提示信息', message: '有未校验通过的信息' });
        }
      },
      //取消操作
      closeDialog() {
        this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
      },
      chooseOrderNo() {
        this.visible = true;
      },
      add() {},
      createFormList() {
        return [
          {
            type: 'INPUT',
            label: '结算汇总单号',
            fieldName: 'sumNo',
            initialValue: '',
            disabled:true
          },
          {
            type: 'SELECT',
            label: '索赔车辆属性',
            fieldName: 'sumType',
            rules: [{ required: true, message: '请选择索赔车辆属性', trigger: 'blur' }],
            initialValue: '',
            disabled:true,
            itemList:this.createDictList('5543'),
          },
          {
            type: 'SELECT',
            label: '单据状态',
            fieldName: 'sumStatus',
            initialValue: '',
            itemList:this.createDictList('5547'),
            disabled:true
          }, {
            type: 'INPUT',
            label: '发票张数',
            fieldName: 'invoiceSheets',
            initialValue: '',
            disabled:true,
          }, {
            type: 'INPUT',
            label: '开票总金额',
            fieldName: 'invoiceAmount',
            initialValue: '',
            disabled:true,
          },{
            type: 'DATE_TIME',
            label: '提交时间',
            dateFormat: 'yyyy-MM-dd',
            fieldName: 'applyDate',
            disabled:true,
            initialValue: '',
          },
          {
            type: 'TEXT_AREA',
            label: '开票备注',
            selfCols: '3',
            fieldName: 'invoiceRemarks',
            initialValue: '',
            disabled:true,
            placeholder: '开票备注...',
          }
        ];
      },
      //结算单列表
      creatHeader() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 100,
            render: (props) => {
              return (
                <div style="text-align:center">
                  <multiuse-button type="text" onClick={() => this.chakan(props.row)} >
                    详情
                  </multiuse-button>
                </div>
              );
            },
          },
          { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
          { title: '经销商名称', dataIndex: 'dealerName', sorter: true },
          { title: '结算批次单号', dataIndex: 'batchNo', sorter: true },
          { title: '索赔单数', dataIndex: 'claimNum', sorter: true },
          { title: '发票张数', dataIndex: 'invoiceSheets', sorter: true },
          { title: '结算金额', dataIndex: 'settleSum', sorter: true },
          { title: '索赔金额', dataIndex: 'claimSum', sorter: true },
          { title: '考核金额', dataIndex: 'assessSum', sorter: true },
          // { title: '税额', dataIndex: 'settleStatusStr', sorter: true },
          { title: '工时费（元）', dataIndex: 'labourAmount', sorter: true },
          { title: '配件费用（元）', dataIndex: 'partAmount', sorter: true },
          { title: '附加费（元）', dataIndex: 'addAmount', sorter: true },
        ];
      },
      //审核列表
      creatHeader1() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          { title: '操作人', dataIndex: 'checkBy', sorter: true },
          { title: '操作时间', dataIndex: 'checkAt', sorter: true },
          { title: '操作后状态', dataIndex: 'statusStr', sorter: true },
          { title: '审核原因', dataIndex: 'checkRemarks', sorter: true }
        ];
      },createFormList2() {
        return [
          {
            type: 'TEXT_AREA',
            label: '审核说明',
            fieldName: 'checkRemarks',
            rules: [],
            selfCols:4,
            placeholder: '请输入审核说明...',
            initialValue: '',
          }
        ];
      },
    }
  };
</script>
<style lang="less" scoped></style>
